package com.example.xwadmin.api.interceptor;

import com.example.xwcommon.entity.Admin;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        //获取请求头信息
        String jwt = request.getHeader("jwttoken");
        if(jwt == null || jwt.trim().equals("")){
            return true;
        }
        Claims claims=null;
        try {//解析jwt
            claims = Jwts.parser().setSigningKey("111222").parseClaimsJws(jwt).getBody();
        }
        catch (ExpiredJwtException e){//过期
            response.setStatus(401);
            response.getWriter().println("{\"code\":4001,\"data\":null,\"msg\":\"登录过期请重新登录\"}");
            return false;
        }
        catch (SignatureException e){//签名错误
            response.setStatus(401);
            response.getWriter().println("{\"code\":4001,\"data\":null,\"msg\":\"登陆凭证签名错误，请重新登录\"}");
            return false;
        }
        //获取用户信息
        Integer id = Integer.parseInt(claims.get("admin_id").toString());
        String name= claims.get("admin_name").toString();
        String loginName = claims.get("admin_loginname").toString();
        List<String> level = (List<String>) claims.get("admin_level");
        List<String> pmses = (List<String>) claims.get("admin_pmses");

        //封装用户信息
        Admin admin=new Admin();
        admin.setAdminId(id);
        admin.setAdminName(name);
        admin.setAdminLoginName(loginName);
        admin.setLevel(level);
        admin.setPmses(pmses);
        //将用户信息放入request/**/
        request.setAttribute("cur_admin",admin);
        System.out.println(request.getAttribute(""+"cur_admin"));
        return true;
    }
}
